package com.pets.web.config;

import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.URLUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.pets.common.utils.CDNUtil;
import com.pets.common.utils.StringUtils;
import com.pets.common.utils.sign.Md5Utils;
import com.pets.common.utils.uuid.UUID;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class RichTextJsonSerializer extends JsonSerializer<String> {

    private static final String REGEX = "https://img\\.weichonchou\\.com/.+(.jpg|.jpeg|.png|.mp4)";
    @Override
    public void serialize(String text, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        List<String> strings = ReUtil.findAllGroup0(REGEX, text);
        if (strings.isEmpty()){
            return;
        }
        String newText = "";
        for (String url : strings) {
            String signUrl = CDNUtil.sign(url);
            newText = text.replaceAll(url, signUrl);
            log.info("intro url签名: old: {} new: {}", url, signUrl);
        }
        jsonGenerator.writeString(newText);
    }

}
